package vn.huync.smsbackupandrestore.others;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xmlpull.v1.XmlSerializer;

import vn.huync.smsbackupandrestore.MyApp;
import vn.huync.smsbackupandrestore.models.ContactModel;
import vn.huync.smsbackupandrestore.models.SmsModel;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import android.util.Xml;
import android.widget.Toast;

import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.DropboxAPI.Entry;
import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.exception.DropboxException;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.FileList;
import com.google.api.services.drive.model.ParentReference;

public class Utils {
	
	static final String DRIVE_ACCOUNT_KEY = "driveAccountKey";
	
	public static void GetListLastestSmsByAddress(ArrayList<SmsModel> fullList, ArrayList<SmsModel> lSmsLastestByAddress)
	{
		lSmsLastestByAddress.clear();
		for(SmsModel sms:fullList){
			SmsModel smsInUniqueList = IsExistAddressInListSms(sms.getAddress(), lSmsLastestByAddress);
			if(smsInUniqueList != null){
				if(sms.getDate() > smsInUniqueList.getDate()){
					lSmsLastestByAddress.remove(smsInUniqueList);
					lSmsLastestByAddress.add(sms);
				}
			}
			else{
				lSmsLastestByAddress.add(sms);
			}
		}
	}
	
	static SmsModel IsExistAddressInListSms(String address, ArrayList<SmsModel> lSms)
	{
		for(SmsModel sms:lSms){
			if(PhoneNumberUtils.compare(sms.getAddress(), address) == true){
				return sms;
			}
		}
		return null;
	}
	
	public static void ReadSMSFromDbToList(Context context, ArrayList<SmsModel> listSms)
	{
		listSms.clear();
		Cursor cursor = context.getContentResolver().query(Uri.parse("content://sms"), null, null, null, null);
		cursor.moveToFirst();
		
		if(cursor.getCount() > 0){
			do{
			   int protocol = cursor.getInt(cursor.getColumnIndex("protocol"));
			   String address = cursor.getString(cursor.getColumnIndex("address"));
			   long date = cursor.getLong(cursor.getColumnIndex("date"));
			   int type = cursor.getInt(cursor.getColumnIndex("type"));
			   String subject = cursor.getString(cursor.getColumnIndex("subject"));
			   String body = cursor.getString(cursor.getColumnIndex("body"));
			   String serviceCenter = cursor.getString(cursor.getColumnIndex("service_center"));
			   int read = cursor.getInt(cursor.getColumnIndex("read"));
			   int status= cursor.getInt(cursor.getColumnIndex("status"));
			   int lock = cursor.getInt(cursor.getColumnIndex("locked"));
			   
			   SmsModel sms = new SmsModel(protocol, address, date, type, subject, body, serviceCenter, read, status, lock);
			   listSms.add(sms);
			}while(cursor.moveToNext());
		}
	}
	
	public static void ShowToast(Context context, String text){
		Toast.makeText(context, text, Toast.LENGTH_LONG).show();
	}
	
	public static void ShowToast(Context context, int textId){
		Toast.makeText(context, textId, Toast.LENGTH_LONG).show();
	}
	
	public static void WriteLog(String text){
		Log.i("DEBUG", text);
	}
	
	public static void ReadContactFromDbToList(Context context, ArrayList<ContactModel> listContact)
	{
		listContact.clear();
		Cursor cursor = context.getContentResolver().query(Phone.CONTENT_URI, null, null, null, null);
		cursor.moveToFirst();
		
		if(cursor.getCount() > 0){
			do{
			   String displayName = cursor.getString(cursor.getColumnIndex(Phone.DISPLAY_NAME));
			   String address = cursor.getString(cursor.getColumnIndex(Phone.NUMBER));
			   String sId = cursor.getString(cursor.getColumnIndex(Phone._ID));
			   int id = Integer.parseInt(sId);
			   ContactModel contact = new ContactModel(id, displayName, address);
			   
			   listContact.add(contact);
			}while(cursor.moveToNext());
		}
	}
	
	public static String GetDisplayNameOfSms(SmsModel sms, ArrayList<ContactModel> lContacts){
		for(ContactModel contact : lContacts){
			if(PhoneNumberUtils.compare(contact.getAddress(), sms.getAddress()) == true)
				return contact.getName();
		}
		return "";
	}
	
	public static String GetDisplayNameOfAddress(String address, ArrayList<ContactModel> lContacts){
		for(ContactModel contact : lContacts){
			if(PhoneNumberUtils.compare(contact.getAddress(), address) == true)
				return contact.getName();
		}
		return "";
	}
	
	public static ArrayList<SmsModel> ListSmsByAddress(ArrayList<SmsModel> fullListSms, String address){
		ArrayList<SmsModel> lSmsByAddress = new ArrayList<SmsModel>();
		for(SmsModel sms: fullListSms){
			if(PhoneNumberUtils.compare(sms.getAddress(), address) == true){
				lSmsByAddress.add(sms);
			}
		}
		return lSmsByAddress;
	}

	public static ArrayList<SmsModel> ReadSmsFromSDCardToList(String filePath)
	{
		ArrayList<SmsModel> lSms = new ArrayList<SmsModel>();
		
		Document doc = null;
	    DocumentBuilderFactory docBuildFact = null;
	    DocumentBuilder docBuilder = null;
	    FileInputStream file = null;
		try {
			file = new FileInputStream(filePath);
		} catch (FileNotFoundException e) {
			Log.e("DEBUG", "File not found : "+filePath);
		}
	    docBuildFact = DocumentBuilderFactory.newInstance();
	    try {
			docBuilder = docBuildFact.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}

	    try {
			doc = docBuilder.parse(file);
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	    
	    Element rootElement = (Element) doc.getDocumentElement();
	    NodeList nlSms = rootElement.getElementsByTagName("sms");
	    for(int i = 0; i < nlSms.getLength(); i++){
	    	
	    	Element elSms = (Element)nlSms.item(i);
	    	int protocol = Integer.parseInt(elSms.getAttribute("protocol"));
		    String address = elSms.getAttribute("address");
		    long date = Long.parseLong(elSms.getAttribute("date"));
		    int type = Integer.parseInt(elSms.getAttribute("type"));
		    String subject = elSms.getAttribute("subject");
		    String body = elSms.getAttribute("body");
		    String serviceCenter = elSms.getAttribute("service_center");
		    int read = Integer.parseInt(elSms.getAttribute("read"));
		    int status= Integer.parseInt(elSms.getAttribute("status"));
		    int lock = Integer.parseInt(elSms.getAttribute("locked"));

		    SmsModel sms = new SmsModel(protocol, address, date, type, subject, body, serviceCenter, read, status, lock);
			lSms.add(sms);
	    }
	    try {
			file.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	    return lSms;
	}
	
	public static void WriteFromListToXML(String filePath, ArrayList<SmsModel> lSms, Handler handler)
	{
		File newxmlfile = new File(filePath);

        try{
            newxmlfile.createNewFile();
        }catch(IOException e)
        {
            Log.e("IOException", "Exception in create new File(");
        }
        FileOutputStream fileos = null;
        try{
            fileos = new FileOutputStream(newxmlfile);

        }catch(FileNotFoundException e)
        {
            Log.e("FileNotFoundException",e.toString());
        }
        XmlSerializer serializer = Xml.newSerializer();

    	try {
			serializer.setOutput(fileos, "UTF-8");
			
        	serializer.startDocument(null, Boolean.valueOf(true));
        	
        	int numSmsBackup = 0;
        	serializer.startTag(null, "sms-list");
        	serializer.attribute(null, "count", Integer.toString(lSms.size()));
        		for(SmsModel model:lSms)
        		{
        			serializer.startTag(null, "sms");
        			serializer.attribute(null, "protocol", Integer.toString(model.getProtocol()));
        			serializer.attribute(null, "address", model.getAddress());
        			serializer.attribute(null, "date", Long.toString(model.getDate()));
        			serializer.attribute(null, "type", Integer.toString(model.getType()));
        			serializer.attribute(null, "subject", model.getSubject());
        			serializer.attribute(null, "body", model.getBody());
        			serializer.attribute(null, "service-center", model.getServiceCenter());
        			serializer.attribute(null, "read", Integer.toString(model.getRead()));
        			serializer.attribute(null, "status", Integer.toString(model.getStatus()));
        			serializer.attribute(null, "locked", Integer.toString(model.getLock()));
        			serializer.endTag(null, "sms");
        			
        			numSmsBackup++;
        			//send message
        			if(handler != null){
        				Message message = new Message();
        				Bundle data = new Bundle();
        				data.putInt("numSmsBackedUp", numSmsBackup);
        				message.setData(data);
        				handler.sendMessage(message);
        			}
        		}
        	serializer.endTag(null, "sms-list");
        	serializer.endDocument();
    	} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static int WriteSmsFromListToDb(Context context, ArrayList<SmsModel> lSms, Handler handler)
	{
		int numSmsRestored = 0;
		
		
		for(SmsModel model:lSms){
			ContentValues values = new ContentValues();
			values.put("protocol", Integer.toString(model.getProtocol()));
			values.put("address", model.getAddress());
			values.put("date", Long.toString(model.getDate()));
			values.put("type", Integer.toString(model.getType()));
			values.put("subject", model.getSubject());
			values.put("body", model.getBody());
			values.put("service_center", model.getServiceCenter());
			values.put("read", Integer.toString(model.getRead()));
			values.put("status", Integer.toString(model.getStatus()));
			values.put("locked", Integer.toString(model.getLock()));
			
			context.getContentResolver().insert(Uri.parse("content://sms"), values);
			numSmsRestored ++;
			
			//send message
			if(handler != null){
				Message message = new Message();
				Bundle data = new Bundle();
				data.putInt("numSmsRestored", numSmsRestored);
				message.setData(data);
				handler.sendMessage(message);
			}
		}
		if(numSmsRestored == 0){
			Message message = new Message();
			Bundle data = new Bundle();
			data.putInt("numSmsRestored", 0);
			message.setData(data);
			handler.sendMessage(message);
		}
		return numSmsRestored;
	}
	
	public static boolean IsExistSmsInList(long date, String address, ArrayList<SmsModel> listSms)
	{
		for(SmsModel sms:listSms){
			if(sms.getDate() == date && sms.getAddress().equals(address))
				return true;
		}
		return false;
	}
	
	public static int[] SyncDropbox(MyApp myApp){
		int[] outArray = new int[2];
		
		//get list file in sdcard
		ArrayList<String> lFilenameSdcard = new ArrayList<String>();
		ArrayList<Long> lFileSizeSdcard = new ArrayList<Long>();
		File dir = new File(myApp.appFolderPath);
		File[] files = dir.listFiles(new FilenameFilter() {
			public boolean accept(File dir, String filename) {
				if(filename.endsWith(".xml"))
					return true;
				else return false;
			}
		});
		for(File file:files){
			lFilenameSdcard.add(file.getName());
			lFileSizeSdcard.add(Long.valueOf(file.length()));
		}
		
		//get list file in dropbox
		DropboxAPI<AndroidAuthSession> dbApi = myApp.mDBApi;
		ArrayList<String> lFilenameDropbox = new ArrayList<String>();
		ArrayList<Long> lFileSizeDropbox = new ArrayList<Long>();
		Entry existEntry = null;
		try {
			existEntry = dbApi.metadata("/", 1000, null, true, null);
		} catch (DropboxException e) {
			e.printStackTrace();
		}
		if(existEntry == null)
			return outArray;
		List<Entry> entries = existEntry.contents;
		if(entries != null){
			for(Entry entry:entries){
				String fileName = entry.fileName();
				if(fileName.endsWith(".xml")){
					lFilenameDropbox.add(fileName);
					lFileSizeDropbox.add(Long.valueOf(entry.bytes));
				}
			}
		}
		
		//upload
		for(int i = 0; i < lFilenameSdcard.size(); i++){
			boolean isExistedInDropbox = false;
			boolean isSameNameButDifferentSize = false;
			for(int j = 0; j < lFilenameDropbox.size(); j++){
				if(lFilenameSdcard.get(i).equals(lFilenameDropbox.get(j))){
					isExistedInDropbox = true;
					if(lFileSizeSdcard.get(i).longValue() != lFileSizeDropbox.get(j).longValue()){
						isSameNameButDifferentSize = true;
					}
					break;
				}
			}
			if(isSameNameButDifferentSize == true || isExistedInDropbox == false ){
				try {
					FileInputStream inputStream = new FileInputStream(files[i]);
					dbApi.putFileOverwrite(lFilenameSdcard.get(i), 
							inputStream, files[i].length(), null);
					outArray[0]++;
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (DropboxException e) {
					e.printStackTrace();
				}
			}
		}
		
		//download
		for(int i = 0; i < lFilenameDropbox.size(); i++){
			boolean isExistedInSdcard = false;
			for(int j = 0; j < lFilenameSdcard.size(); j++){
				if(lFilenameDropbox.get(i).equals(lFilenameSdcard.get(j))){
					isExistedInSdcard = true;
					break;
				}
			}
			if(isExistedInSdcard == false ){
				try {
					FileOutputStream outputStream = new FileOutputStream(myApp.appFolderPath+lFilenameDropbox.get(i));
					dbApi.getFile("/"+lFilenameDropbox.get(i), null, 
							outputStream, null);
					outArray[1]++;
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (DropboxException e) {
					e.printStackTrace();
				}
			}
		}
		return outArray;
	}
	
	static void insertFile(Drive service, File fileLocal, String title, String mimeType) throws UserRecoverableAuthIOException{
		try{
		com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File();
        body.setTitle(title);
        body.setMimeType(mimeType);
        body.setParents(Arrays.asList(new ParentReference().setId("appdata")));

        FileContent mediaContent = new FileContent(mimeType, fileLocal);
        com.google.api.services.drive.model.File file = service.files().insert(body, mediaContent).execute();
        if (file != null) {
          Log.i("", "File uploaded: " + file.getTitle());
        }
      } catch (UserRecoverableAuthIOException exception) {
    	  throw exception;
      } catch (IOException ex) {
    	  ex.printStackTrace();
      }
	}
	
	static void downloadFileDrive(Drive service, String filePath, com.google.api.services.drive.model.File driveFile){
		if (driveFile.getDownloadUrl() != null && driveFile.getDownloadUrl().length() > 0) {
	      try {
	        HttpResponse resp =  service.getRequestFactory().buildGetRequest(new GenericUrl(driveFile.getDownloadUrl()))
	                .execute();
	        InputStream inputStream = resp.getContent();
	        
	        OutputStream outputStream = new FileOutputStream(new File(filePath));
	        
	        int read = 0;
			byte[] bytes = new byte[1024];
	        while ((read = inputStream.read(bytes)) != -1) {
				outputStream.write(bytes, 0, read);
			}
	        inputStream.close();
	        outputStream.close();
 
	      } catch (IOException e) {
	        e.printStackTrace();
	      }
	    } else {
	      // The file doesn't have any content stored on Drive.
	      Log.i("", "File not found");
	    }
	}
	
	public static int[] syncDrive(String appFolderPath, Drive service, MyApp myApp) throws UserRecoverableAuthIOException{
		
		int[] outArray = new int[2];
		
		Log.i("", "Begin sync drive");
		//get list file in sdcard
		ArrayList<String> lFilenameSdcard = new ArrayList<String>();
		ArrayList<Long> lFileSizeSdcard = new ArrayList<Long>();
		File dir = new File(myApp.appFolderPath);
		File[] files = dir.listFiles(new FilenameFilter() {
			public boolean accept(File dir, String filename) {
				if(filename.endsWith(".xml"))
					return true;
				else return false;
			}
		});
		for(File file:files){
			lFilenameSdcard.add(file.getName());
			lFileSizeSdcard.add(Long.valueOf(file.length()));
		}
		
		//get list file in drive
		List<com.google.api.services.drive.model.File> listDriveFiles = new ArrayList<com.google.api.services.drive.model.File>();
		ArrayList<String> lFilenameDrive = new ArrayList<String>();
		ArrayList<Long> lFileSizeDrive = new ArrayList<Long>();
		try {
			Files.List request;
			request = service.files().list();
			request.setQ("'appdata' in parents");

			  do {
			    try {
			      FileList driveFiles = request.execute();
			      listDriveFiles.addAll(driveFiles.getItems());
			      request.setPageToken(driveFiles.getNextPageToken());
			    } catch (IOException e) {
			      System.out.println("An error occurred - syncDrive - get list file: " + e);
			      request.setPageToken(null);
			      return null;
			    }
			  } while (request.getPageToken() != null && request.getPageToken().length() > 0);
		} catch (IOException e1) {
			e1.printStackTrace();
			return null;
		}
		Log.i("", "There are " + listDriveFiles.size() + " files in Drive");
		
		for(com.google.api.services.drive.model.File driveFile : listDriveFiles){
			String fileName = driveFile.getTitle();
			if(fileName.endsWith(".xml")){
				lFilenameDrive.add(fileName);
				lFileSizeDrive.add(Long.valueOf(driveFile.getFileSize()));
			}
		}
		//upload
		for(int i = 0; i < lFilenameSdcard.size(); i++){
			boolean isExistedInDrive = false;
			boolean isSameNameButDifferentSize = false;
			int sameNameIndexDrive = -1;
			for(int j = 0; j < lFilenameDrive.size(); j++){
				if(lFilenameSdcard.get(i).equals(lFilenameDrive.get(j))){
					isExistedInDrive = true;
					if(lFileSizeSdcard.get(i).longValue() != lFileSizeDrive.get(j).longValue()){
						isSameNameButDifferentSize = true;
						sameNameIndexDrive = j;
					}
					break;
				}
			}
			if(isExistedInDrive == false ){
				insertFile(service, files[i], files[i].getName(), "application/xml");
				outArray[0]++;
			}
			else if(isSameNameButDifferentSize == true){
				deleteFileDrive(myApp, listDriveFiles.get(sameNameIndexDrive), service);
				
				insertFile(service, files[i], files[i].getName(), "application/xml");
				outArray[0]++;
			}
		}
		Log.i("", "There are " + outArray[0] + " files uploaded");
		
		//download
		for(com.google.api.services.drive.model.File driveFile : listDriveFiles){
			boolean isExistedInSdcard = false;
			for(int j = 0; j < lFilenameSdcard.size(); j++){
				if(driveFile.getTitle().equals(lFilenameSdcard.get(j))){
					isExistedInSdcard = true;
					break;
				}
			}
			if(isExistedInSdcard == false ){
				downloadFileDrive(service, myApp.appFolderPath + driveFile.getTitle(), driveFile);
				outArray[1]++;
			}
		}
		Log.i("", "There are " + outArray[1] + " files downloaded");
		
		return outArray;
	}
	
	public static boolean DeleteFileDropbox(MyApp myApp, String filename){
		DropboxAPI<AndroidAuthSession> dbApi = myApp.mDBApi;
		try {
			dbApi.delete(filename);
		} catch (DropboxException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public static boolean deleteFileDrive(MyApp myApp, String filename, Drive service){
		if(service == null)
			return false;
		//get list file in drive
		List<com.google.api.services.drive.model.File> listDriveFiles = new ArrayList<com.google.api.services.drive.model.File>();
		try {
			Files.List request;
			request = service.files().list();
			request.setQ("'appdata' in parents");

			  do {
			    try {
			      FileList driveFiles = request.execute();
			      listDriveFiles.addAll(driveFiles.getItems());
			      request.setPageToken(driveFiles.getNextPageToken());
			    } catch (IOException e) {
			      request.setPageToken(null);
			      return false;
			    }
			  } while (request.getPageToken() != null && request.getPageToken().length() > 0);
		} catch (IOException e1) {
			e1.printStackTrace();
			return false;
		}
		
		for(com.google.api.services.drive.model.File driveFile : listDriveFiles){
			if(driveFile.getTitle().equals(filename)){
				try {
			      service.files().delete(driveFile.getId()).execute();
			    } catch (IOException e) {
			      System.out.println("An error occurred - deleteFileDrive - delete file: " + e);
			    }
			}
		}
		return true;
	}
	
	public static boolean deleteFileDrive(MyApp myApp, com.google.api.services.drive.model.File file, Drive service){
		if(service == null)
			return false;
		
		try {
	      service.files().delete(file.getId()).execute();
	    } catch (IOException e) {
	      System.out.println("An error occurred - deleteFileDrive - delete file: " + e);
	      return false;
	    }
		return true;
	}
	
	public static boolean isInternetConnected(Context context){
		ConnectivityManager connect =  (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if(connect.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED
				|| connect.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED){
			return true;
		}
		return false;
	}
	
	public static String getDriveUsername(Context context){
		SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
		return preferences.getString(DRIVE_ACCOUNT_KEY, null);
	}
	
	public static void logoutDrive(Context context){
		SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
		Editor editor = preferences.edit();
		editor.putString(DRIVE_ACCOUNT_KEY, null);
		editor.commit();
	}
	
	public static void syncAll(MyApp myApp, Context context, SyncListener syncListener){
		if(myApp.isLogedInDropbox){
			final int[] outArray = Utils.SyncDropbox(myApp);
			
			if(syncListener != null)
				syncListener.onSyncDropboxDone(outArray[0], outArray[1]);
		}
		
		if(Utils.getDriveUsername(context) != null){
			try {
				int[] outArrayDrive = Utils.syncDrive(myApp.appFolderPath, myApp.service, myApp);
				
				if(syncListener != null && outArrayDrive != null)
					syncListener.onSyncDriveDone(outArrayDrive[0], outArrayDrive[1]);
			} catch (UserRecoverableAuthIOException e) {
				if(syncListener != null)
					syncListener.onUserRecoverableAuthIOException(e);
			}
		}
		
		if(syncListener != null)
			syncListener.onSyncDone();
	}
	
	public interface SyncListener{
		void onSyncDone();
		void onSyncDropboxDone(int upload, int download);
		void onSyncDriveDone(int upload, int download);
		void onUserRecoverableAuthIOException(UserRecoverableAuthIOException e);
	}
	
	public static void autoLoginDrive(MyApp myApp, Context context){
		if(myApp.credential == null)
			myApp.credential = GoogleAccountCredential.usingOAuth2(context, Arrays.asList(DriveScopes.DRIVE, DriveScopes.DRIVE_APPDATA));
		String driveUsername = Utils.getDriveUsername(context);
		myApp.credential.setSelectedAccountName(driveUsername);
    	myApp.service = new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), myApp.credential).build();
	}
}
